import {Component, OnInit, ViewChild} from "@angular/core";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {Router, ActivatedRoute} from "@angular/router";
import {ResponseUtil} from "../../../../util/response-util";
import {PageSubject} from "../../../../util/page-subject";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {MenusService} from "../menus.service";
import {MsgConstants, API} from "../../../../constants/constants";
import {MsgResult} from "../../../../models/msg-result";
import {OneOperationComponent} from "../../../../widgets/one-operation/one-operation.component";
import {TableUtil} from "../../../../util/table-util";
import {TreeUtil} from "../../../../util/tree-util";
import {Observable} from "rxjs/Observable";

declare var $;

@Component({
  selector: 'app-menu-operation',
  templateUrl: './menu-operation.component.html'

})
export class MenuOperationComponent implements OnInit {
  @ViewChild(OneOperationComponent) operation: OneOperationComponent;

  menuId: string;

  operaIdArr: Array<string> = [];

  table;

  treeObj;
  constructor(private router: Router,
              private route: ActivatedRoute,
              private tableUtil: TableUtil,
              private treeUtil: TreeUtil,
              private responseUtil: ResponseUtil,
              private pageSubject: PageSubject,
              private menusService: MenusService,
              private dialogService: OneDialogService) {
  }

  ngOnInit() {
    this.getMenuDatas();

    this.pushPage();
    if (!!this.route.snapshot.params["menuId"]) {
      this.menuId = this.route.snapshot.params["menuId"];
      this.initOperationData();
    }
  }

  /**
   * 面包屑导航
   */
  private pushPage() {
    let path = new Path("权限系统", "");
    this.pageSubject.pushPage("菜单管理", "分配操作", path);
  }

  /**
   * 刷新页面
   */
  reLoad() {
    this.table.bootstrapTable('refresh');
  }

  /**
   * 保存操作
   * 1.点击保存时，获取数据；
   * 2.移除修改行，点击事件；
   * 3.绑定所有行，点击事件；
   * 4.提交编辑后的数据；
   */
  saveOperation() {
    //获取数据
    let params = this.getEditRowData();
    this.dealClickEventAfterGetDat();
    //提交数据
    this.menusService.addOrUpdateOpreations(params, this.menuId).subscribe(
      result => this.responseUtil.success(result, this.getOperationAddFormData),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 对添加修改结果进行处理
   * @param result
   */
  private getOperationAddFormData = (result: MsgResult) => {
    if (MsgConstants.MSG_CODE_OK == result.code) {
      this.reLoad();
    }
  }

  /**
   * 获取数据后，处理点击事件
   */
  dealClickEventAfterGetDat() {
    //提交成功,清楚data-edit
    this.table.removeData("edit");
    this.table.find(" .one-table-edit input").each(function (i, elem) {
      var text = $(elem).val();
      $(elem).parent().html(text);
    });
    //绑定点击事件
    this.table.find("tbody tr").removeData("edit").off("click").on("click", (e) => this.rowClick(e));
    //去掉新增行的input或触发刷新
    // this.reLoad();

  }

  goBack() {
    this.router.navigate(['..'], {relativeTo: this.route});
  }

  /**
   * 删除操作
   * 1.未勾选数据时，模态框提示；
   * 2.勾选一条或多条进行删除
   */
  deleteOperation() {
    this.getSelectedCheckboxValue();
    if (this.operaIdArr.length == 0 || this.operaIdArr[0] == "") {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.dialogService.modalInfoWithCancelBtn("确定删除？", this.requestDelete, this.cancelDelOper);
    }
  }

  /**
   * 确认删除按钮
   * 1.单一删除；
   * 2.批量删除；
   */
  private requestDelete = () => {
    //调用后端接口
    this.menusService.delOperations(this.operaIdArr).subscribe(
      result => this.responseUtil.success(result, this.processDeleteResult),
      error => this.responseUtil.error(error)
    );
  }

  /**
   * 对删除结果进行处理
   * @param result
   */
  private processDeleteResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message);
      this.clearArrayData();
      this.reLoad();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
      this.clearArrayData();
    }
  }

  /**
   * 取消删除
   * 1.取消删除时，清空数组；
   */
  private cancelDelOper = () => {
    if (this.operaIdArr.length != 0) {
      this.clearArrayData();
    }
  }

  /**
   * 获取勾选复选框的值
   * 1.遍历勾选的复选框；
   * 2.把value值存入数组；
   */
  getSelectedCheckboxValue() {
    $(".table tr td:first-child input[type=checkbox]:checked").each(function (i, elem) {
      let val = $(elem).val();
      !!val && this.operaIdArr.push(val);
    }.bind(this));
  }

  /**
   * 清空数组
   */
  private clearArrayData() {
    this.operaIdArr.splice(0, this.operaIdArr.length);
  }

  /**
   * 处理编辑行数据
   * @returns {string}
   */
  private getEditRowData() {
    let isPass = true, errMsg = "";
    let datas: string = "";
    this.table.find("tbody tr").each(function (i, n) {
      if ('1' != $(n).data('edit')) {
        return;
      }
      var data = new Array(10);
      $(n).find("td").each(function (i, m) {
        data[i] = $(m).find("input").val();
      });


      if (!(/^\d+$/.test(data[1]))) {
        isPass = false;
        errMsg = "顺序必须是正整数!";
        return;
      }

      if (!(/^[a-zA-Z0-9_]+$/.test(data[2]))) {
        errMsg = "操作编码只能是英文字母,数字，下划线!";
        isPass = false;
        return;
      }
      if (!(/^([A-Za-z]|[\u4E00-\u9FA5])+$/.test(data[3]))) {
        errMsg = "操作名只能输入英文或汉字!";
        isPass = false;
        return;
      }
      if (!(/^$|^[a-zA-Z\s]+$/.test(data[4]))) {
        errMsg = "操作样式可以是空或英文及空格!";
        isPass = false;
        return;
      }
      if (!(/^$|^[a-zA-Z]+$/.test(data[5]))) {
        errMsg = "请输入正确的操作函数,可为空或英文";
        isPass = false;
        return;
      }

      if (!(/^$|^[a-zA-Z\s]+$/.test(data[6]))) {
        errMsg = "URL可以为空或英文字母与空格!";
        isPass = false;
        return;
      }

      datas = "id=" + data[0] + "&operOrder=" + data[1] + "&operationCode=" + data[2] + "&name=" + data[3] + "&cssName=" + data[4]
        + "&bindFun=" + data[5] + "&url=" + data[6] + "&remark=" + data[7] + "&isValid=" + data[8] + "&isShow=" + data[9];
    });
    if (isPass) {
      return datas;
    }
    this.dialogService.modalInfo(errMsg);
    return null;
  }


  rowClick(event) {
    let isEdit = this.table.data("edit");
    let tr = event.currentTarget;

    if ("1" != isEdit) {
      //添加行
      this.editRow(tr);
      this.table.data('edit', "1");
      this.table.find("tr").off("click");
    } else {
      //提示保存
      this.dialogService.infoWithCancelBtn("有数据未保存，是否先保存？", () => this.saveOperation())
    }
  }

  editRow(tr) {
    $(tr).find("td").each(function (i, n) {
      if ($(n).children().length == 0) {
        var content = $(n).html();
        $(n).addClass("one-table-edit").html('<input type="text">').find("input").val(content);
      }
    }).parent().data('edit', "1");
  }

  addOperation() {
    let isEdit = this.table.data("edit");
    if ("1" != isEdit) {
      //添加行
      this.addRow();
      this.table.data('edit', "1");
    } else {
      //提示保存
      this.dialogService.infoWithCancelBtn("有数据未保存，是否先保存？", () => this.saveOperation());
    }
  }

  addRow() {
    this.table.bootstrapTable('append', this.appendData());
    $("tbody tr:last-child", "#one_table_operation").find("td").each(function () {
      if ($(this).children().length == 0) {
        var content = $(this).html();
        $(this).addClass("one-table-edit").html('<input type="text">').find("input").val(content);
      }
    }).parent().data('edit', "1")
      .css("padding-top", "13px");
  }

  appendData() {
    let append = [{
      id: '',
      operOrder: '',
      operationCode: '',
      name: '',
      cssName: '',
      bindFun: '',
      url: '',
      remark: '',
      isValid: '',
      isShow: ''
    }];
    return append;
  }

  initOperationData() {
    // this.table = $('#one_table_operation').bootstrapTable({
    this.table = this.tableUtil.load("one_table_operation",{

      columns: [
        {  field: 'id',  width:'50',  title: '<input type="checkbox" />',
                     formatter: function (value) {
                    return '<input type= "checkbox" value="' + value + '">';
        }  },
        { field: 'operOrder', title: '显示顺序',  align: "right",  halign: "left", width:'80' },
        { field: 'operationCode', title: '操作编码',  align: "left", halign: "left"  },
        { field: 'name',  title: '操作名称',  align: "left",  halign: "left" },
        { field: 'cssName',  title: '操作样式',  align: "left", halign: "left" },
        { field: 'bindFun', title: '操作函数',  align: "left",  halign: "left" },
        {  field: 'url',  title: 'URL',  align: "left",  halign: "left"  },
        {  field: 'remark',  title: '备注',  align: "left",  halign: "left"  },
        {
          field: "isValid", title: "有效",width:'50', formatter: function (value) {
          if (value == "1") {
            return '<input type= "checkbox" checked value= 1>';
          }
          if (value != "1") {
            return '<input type= "checkbox" value= 0>';
          }
          return value;
        },
        }, {
          field: "isShow", title: "显示",width:'50', formatter: function (value) {
            if (value == "1") {
              return '<input type= "checkbox" checked value= 1>';
            }
            if (value != "1") {
              return '<input type= "checkbox" value= 0>';
            }
            return value;
          }
        }
      ],
      undefinedText: " ",
      height: 711,
      toolbar: "#one_toolbar_operation",
      url: API.getAllOprsByMenuId,
      method: 'post',
      contentType: "application/x-www-form-urlencoded",
      //传递附加参数
      queryParams: (params) => {
        params.menuId = this.menuId;
        return params;
      },
      //返回数据处理器
      responseHandler: (result) => {
        this.responseUtil.preSuccess(result);
        return {data: result.data};
      },
      onClickCell: (field, value, row, element) => {

        if ("isValid" == field || "isShow" == field) {
          this.updateCheckValue(element);
        }
      },
      onLoadSuccess: () => {
        this.table.removeData("edit");
        this.bindRowClick();
      }
    });
  }

  private bindRowClick() {
    this.table.find("tbody tr").off("click").on("click", (e) => this.rowClick(e));
  }

  /**
   *复选框勾选赋值处理
   * @param element
   */
  updateCheckValue(element) {
    $(element.children()[0]).attr('value', element.children()[0].checked ? 1 : 0);
    element.attr('value', element.children()[0].checked ? 1 : 0);
  }

  /**
   * 暂未使用
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private selectOperType(value, row, index) {

    if(value == '添加') {
      return `<div style="position:relative;">
                  <select class="multiselect form-control pollutant" id=""  onchange="document.getElementById('input').value=this.value">
                      <option value="添加" selected>添加</option>
                      <option value="删除" >删除</option>
                      <option value="修改" >修改</option>
               </select>
              <input id="input" name="input"style="position:absolute;width:99px;height:16px;left:1px;top:2px;border-bottom:0px;border-right:0px;border-left:0px;border-top:0px;"> 
          </div> `;
    }

    if(value == '删除') {
      return `
          <div style="position: relative;width:99px;height:16px;" onclick="">
              <input id="input" name="input" style="width:99px;height:16px;" value=""> 
                <ul  style="position: absolute;top: 100%;left: 0;background: #fff;display:none">
                  <li>添加</li>
                  <li>删除</li>
                  <li>修改</li>
                </ul>
          </div>
          <!--<select class="multiselect form-control pollutant" id="">-->
                      <!--<option value="添加" >添加</option>-->
                      <!--<option value="删除" selected>删除</option>-->
                      <!--<option value="修改" >修改</option>-->
               <!--</select>-->
`;
    }
    if(value == '修改') {
      return `<select class="multiselect form-control pollutant" id="">
                      <option value="添加" >添加</option>
                      <option value="删除" >删除</option>
                      <option value="修改" selected>修改</option>
               </select>`;
    }

    if(!!value){
      return value;
    }
  }



  /**
   * 获取菜单数据信息
   */
  getMenuDatas() {
    this.menusService.getMenus().subscribe(
      result => this.responseUtil.success(result, this.processMenuTreeResult),
      message => this.responseUtil.error(message)
    );
  }
  private processMenuTreeResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.initMenusTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 把菜单格式化菜单树
   *
   * @param menus: 菜单数据
   */
  initMenusTree(menus) {
    //初始化菜单树
    let setting = {
      callback: {
        onClick: this.clickTree
      }
    };

    let zNodes =this.treeUtil.wrapToStandard(menus);
    //把树放进页面
    this.treeObj = $.fn.zTree.init($("#menuinfo_ZTree_for_opertion"), setting, zNodes);

  }

  /**
   *  菜单的点击事件
   * @param event
   * @param treeId
   * @param treeNode
   */
  clickTree = (event, treeId, treeNode) =>{
    // 获取菜单id
    this.menuId = treeNode.id;
    this.reLoad();
  }

}
